package gold.digger;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC97 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        class Triple {
            public int i;
            public int j;
            public int k;

            public Triple(int i, int j, int k) {
                this.i = i;
                this.j = j;
                this.k = k;
            }

            @Override
            public boolean equals(Object o) {
                if (this == o) return true;
                if (o == null || getClass() != o.getClass()) return false;

                Triple triple = (Triple) o;

                return i == triple.i && j == triple.j && k == triple.k;
            }

            @Override
            public int hashCode() {
                return i + j + k;
            }

        }

        public Map<Triple, Boolean> memo = new HashMap<>();

        public boolean isInterleave(String s1, String s2, String s3) {
            int len1 = s1.length() - 1, len2 = s2.length() - 1, len3 = s3.length() - 1;
            if (len1 + len2 + 1 != len3) return false;
            return isInterleaveRecur(s1, s2, s3, len1, len2, len3);
        }

        public boolean isInterleaveRecur(String s1, String s2, String s3, int len1, int len2, int len3) {
            if (len1 + len2 + 1 != len3) return false;
            if (len1 == -1 && len2 == -1 && len3 == -1) return true;

            Triple curKey = new Triple(len1, len2, len3);
            if (memo.containsKey(curKey)) return memo.get(curKey);

            boolean result = false;
            if (len3 >= 0 && len2 >= 0 && len1 >= 0 && s3.charAt(len3) == s1.charAt(len1) && s3.charAt(len3) == s2.charAt(len2))
                result = isInterleaveRecur(s1, s2, s3, len1 - 1, len2, len3 - 1) || isInterleaveRecur(s1, s2, s3, len1, len2 - 1, len3 - 1);
            else if (len3 >= 0 && len1 >= 0 && s3.charAt(len3) == s1.charAt(len1))
                result = isInterleaveRecur(s1, s2, s3, len1 - 1, len2, len3 - 1);
            else if (len3 >= 0 && len2 >= 0 && s3.charAt(len3) == s2.charAt(len2))
                result = isInterleaveRecur(s1, s2, s3, len1, len2 - 1, len3 - 1);
            else result = false;

            memo.put(curKey, result);
            return result;
        }

    }

    public void run() {
        Solution solution = new Solution();
        String s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc";
//        String s1 = "ab", s2 = "ce", s3 = "acbe";
        System.out.println(solution.isInterleave(s1, s2, s3));
    }

    public static void main(String[] args) throws Exception {
        LC97 an = new LC97();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
